<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Items extends Controller_Main {
    public function after(){
        $this->scripts[]='media/js/items.js';
        parent::after();
    }

    public function before(){
        parent::before();
    }

    public function action_index(){
        Request::current()->redirect('items/itemTypes');
    }
    
    public function action_itemtypes(){
        $view = View::factory('items/itemtypes');
        $this->template->content = $view;
        $this->addTopActionMenu('Dodaj produkt', URL::site('items/additem'));
        $model = new Model_Itemtype();
        $r = $model->find_all();
        $data = ORM::damnArray($r);
        
        $view->data = $data;
    }
    
    public function action_additem(){
        $this->addTopActionMenu('Lista produktów', URL::site('items/itemtypes'));
        $view = View::factory('items/additem');
        $this->template->content = $view;
        $id = Request::current()->param('id');
        if($_POST['id']){
            $id = $_POST['id'];
        }
        if($_REQUEST['status']){
            $status = $_REQUEST['status'];
        }
        
        if($id){
            $model = new Model_Itemtype($id);
        }else{
            $model = new Model_Itemtype();
        }
        if(strtolower($_SERVER['REQUEST_METHOD'])=='post'){
            $postValidator = Validation::factory($_POST);
            $postValidator->rule('name', 'not_empty');
            $postValidator->rule('name', 'min_length', array(':value', 4));

            if($postValidator->check()){
                $data['name'] = Request::current()->post('name');
                $data['category'] = Request::current()->post('category');
                $data['producer'] = Request::current()->post('producer');
                $data['price'] = Request::current()->post('price');
                $data['description'] = Request::current()->post('description');
                $model->values($data);
                $model->save();
                Request::current()->redirect('items/additem/'.$model->id.'?status=save_success');
            }else{
                $errors[] = 'Błąd zapisu. Nazwa nie może być pusta';
//                $errors[] = $postValidator->errorsStr();
            }
        }else{
            $model = new Model_Itemtype($id);
            $data = $model->as_array();
        }
        
        $view->status = $status;
        $view->data = $data;
        $view->errors = $errors;
        $view->id = $id;
    }

} 